package org.xenon.vote.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xenon.vote.model.pojo.vo.Captcha;
import org.xenon.vote.model.pojo.vo.Result;
import org.xenon.vote.service.CaptchaService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private final CaptchaService captchaService;

    public CaptchaController(CaptchaService captchaService) {
        this.captchaService = captchaService;
    }

    @GetMapping("/get")
    public void getCaptcha(HttpServletRequest req, HttpServletResponse resp) {
        Captcha captcha = captchaService.getCaptcha(req.getSession().getId());
        System.out.println("验证码下发: " + captcha.getText());
        try {
            Captcha.output(captcha.getImg(), resp.getOutputStream());
        } catch (IOException e) {
            System.out.println("验证码下发错误");
        }
    }

    /**
     * 网页判断自己是否已登录
     */
    @GetMapping("/login")
    public Result login (HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session.getAttribute("user") == null)
            return new Result(false, "");
        String name = (String) session.getAttribute("user");
        return new Result(true, name);
    }
}
